package huyaoying.study.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

/**
 * Java NIO通道之间的数据传输
 * FileChannel.transferTo()方法
 *      transferTo()方法用来从FileChannel到其他通道的数据传输。
 *
 * FileChannel.transferFrom()方法
 *      transferFrom()方法允许从源通道到FileChannel的数据传输。
 *
 * @author huyaoying
 * @date 2022/2/8
 */
public class TransferDemo {
    public static void main(String[] argv) throws Exception {
        String relativelyPath = System.getProperty("user.dir") + "/src/main/resources" ;
        // 输入文件路径
        String[] iF = new String[] { relativelyPath + "/input1.txt", relativelyPath + "/input2.txt",
                                     relativelyPath + "/input3.txt", relativelyPath + "/input4.txt" };
        // 输出文件路径
        String oF = relativelyPath + "/combine_output.txt";

        // 输出流 通道
        FileOutputStream output = new FileOutputStream(new File(oF));
        WritableByteChannel targetChannel = output.getChannel();
        for (int j = 0; j < iF.length; j++) {

            // 输入流 通道
            FileInputStream input = new FileInputStream(iF[j]);
            FileChannel inputChannel = input.getChannel();
            // FileChannel.transferTo(): transferTo()方法用来从FileChannel到其他通道的数据传输。
            inputChannel.transferTo(0, inputChannel.size(), targetChannel);

            // 关闭通道 关闭流
            inputChannel.close();
            input.close();
        }

        // 关闭通道 关闭流
        targetChannel.close();
        output.close();
        System.out.println("All jobs done...");
    }
}
